﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using System.Text.RegularExpressions;
using Aij1.Utils;

namespace Aij1
{
    public class Global : System.Web.HttpApplication
    {

        protected void Application_Start(object sender, EventArgs e)
        {

        }

        protected void Session_Start(object sender, EventArgs e)
        {

        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            string originalPath = Context.Request.Path.ToLower();
            if (Regex.IsMatch(originalPath, ".htm\\b") &&
                (RewriteUrl(originalPath, "news")
                || RewriteUrl(originalPath, "gallery")
                || RewriteUrl(originalPath, "special")
                || RewriteUrl(originalPath, "shop")
                || RewriteUrl(originalPath, "albumcenter")
                || RewriteUrl(originalPath, "newscenter")
                || RewriteUrl(originalPath, "guestbook")
                || RewriteUrl(originalPath, "shopdetails")
                ))
            {
            }
        }

        bool RewriteUrl(string originalPath, string name)
        {
            Regex reg = new Regex(name + "(_(?<id>\\d+))?(_p(?<page>\\d+))?.htm");
            var matchs = reg.Matches(originalPath);
            int id = 0;
            int page = 0;
            if (matchs.Count <= 0) return false;

            page = CommOp.ToInt(matchs[0].Groups["page"].Value);
            id = CommOp.ToInt(matchs[0].Groups["id"].Value);
            string request = "";
            if (id > 0 && page > 0)
            {
                request = "?Id=" + id + "&Page=" + page;
            }
            else if (id > 0)
            {
                request = "?Id=" + id;
            }
            else if (page > 0)
            {
                request += "?Page=" + page;
            }

            string newPath = reg.Replace(originalPath, name + ".aspx" + request);

            Context.RewritePath(newPath);
            return true;
        }

        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {

        }

        protected void Application_Error(object sender, EventArgs e)
        {

        }

        protected void Session_End(object sender, EventArgs e)
        {

        }

        protected void Application_End(object sender, EventArgs e)
        {

        }
    }
}